<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="cardbox">
      <el-card class="box-card">
        <el-row>
          <el-col :span="8">
            <el-input
              placeholder="请输入内容"
              v-model="pageinfo.query"
              class="input-with-select"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchUsers"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addUsers">添加用户</el-button>
          </el-col>
        </el-row>
        <div class="tablebox">
          <el-table :data="userList" border style="width: 100%">
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="username" label="姓名"> </el-table-column>
            <el-table-column prop="email" label="邮箱"> </el-table-column>
            <el-table-column prop="mobile" label="电话"> </el-table-column>
            <el-table-column prop="role_name" label="角色"> </el-table-column>
            <el-table-column prop="mg_state" label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.mg_state"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="changeState(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  icon="el-icon-edit"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)"
                ></el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row.id)"
                ></el-button>
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-setting"
                  @click="setRole(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageinfo.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageinfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.total"
        >
        </el-pagination>
      </el-card>
    </div>
    <!-- 添加模态框 -->
    <el-dialog title="添加用户" :visible.sync="addFormVisible">
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addokForm">确定</el-button>
          <el-button @click="addFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑模态框 -->
    <el-dialog title="编辑用户" :visible.sync="editFormVisible">
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editokForm">确定</el-button>
          <el-button @click="editFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配角色模态框 -->
    <el-dialog title="收货地址" :visible.sync="roleFormVisible">
      <el-form :model="roleForm">
        <p>当前的用户：{{ currentUser.username }}</p>
        <p>当前的角色：{{ currentUser.role_name }}</p>
        <el-form-item label="分配角色">
          <el-select v-model="roleForm.currentId" placeholder="请选择角色">
            <el-option
              :label="item.roleName"
              :value="item.id"
              v-for="item in roleList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleHandle">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsersApi,
  getStatusApi,
  addUsersApi,
  editUsersApi,
  deleteUsersApi,
  getRoleApi,
  setroleApi,
} from "@/http/api";
import { Message } from "element-ui";
export default {
  name: "",
  components: {},
  data() {
    var regEmail = (rule, value, callback) => {
      const emailReg =
        /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (!emailReg.test(value)) {
        return callback(new Error("你输入的邮箱格式有误，应为xxx@xxx.com"));
      }
      callback();
    };
    var regMobile = (rule, value, callback) => {
      const mobileReg = /^1[356789]\d{9}$/;
      if (!mobileReg.test(value)) {
        return callback(new Error("你输入的手机号有误"));
      }
      callback();
    };
    return {
      currentId: 0,
      currentUser: {},
      userList: [],
      total: 0,
      roleList: [],
      pageinfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      formLabelWidth: "120px",
      addFormVisible: false,
      editFormVisible: false,
      roleFormVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      roleForm: {},
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: regEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: regMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUsers();
  },
  mounted() {},
  methods: {
    // 分配角色
    setRoleHandle() {
      setroleApi(this.currentUser.id, { rid: this.roleForm.currentId }).then(
        (res) => {
          console.log(res);
          if (res.data.meta.status == 200) {
            Message({
              message: res.data.meta.msg,
              type: "success",
            });
          } else {
            Message({
              message: res.data.meta.msg,
              type: "error",
            });
          }
          this.roleFormVisible = false;
          this.getUsers();
        }
      );
    },
    // 打开分配角色模态框
    setRole(row) {
      this.roleFormVisible = true;
      const { id, username, role_name } = row;
      console.log(row);
      this.currentUser = { username, role_name, id };
      getRoleApi().then((res) => {
        console.log(res);
        if (res.data.meta.status == 200) {
          this.roleList = res.data.data;
          Message({
            message: res.data.meta.msg,
            type: "success",
          });
        } else {
          Message({
            message: res.data.meta.msg,
            type: "error",
          });
        }
      });
    },
    // 编辑用户
    editokForm() {
      this.$refs.addForm.validate((valid) => {
        if (!valid) return false;
        editUsersApi(this.currentId, this.addForm).then((res) => {
          console.log(res);
          if (res.data.meta.status == 200) {
            Message({
              message: res.data.meta.msg,
              type: "success",
            });
          } else {
            Message({
              message: res.data.meta.msg,
              type: "error",
            });
          }
        });
        this.editFormVisible = false;
        this.getUsers();
      });
    },
    // 添加用户
    addokForm() {
      this.$refs.addForm.validate((valid) => {
        if (!valid) return false;
        addUsersApi(this.addForm).then((res) => {
          if (res.data.meta.status == 201) {
            Message({
              message: res.data.meta.msg,
              type: "success",
            });
          } else {
            Message({
              message: res.data.meta.msg,
              type: "error",
            });
          }
        });
        this.addFormVisible = false;
        this.getUsers();
      });
    },
    // 点击添加打开模态框
    addUsers() {
      this.addFormVisible = true;
    },
    // 搜索功能
    searchUsers() {
      this.getUsers();
    },
    // 获取用户列表信息
    getUsers() {
      getUsersApi(this.pageinfo).then((res) => {
        console.log(res);
        if (res.data.meta.status == 200) {
          this.userList = res.data.data.users;
          this.total = res.data.data.total;
          Message({
            message: res.data.meta.msg,
            type: "success",
          });
        } else {
          Message({
            message: res.data.meta.msg,
            type: "error",
          });
        }
      });
    },
    // 改变用户状态
    changeState(row) {
      console.log(row);
      const { id, mg_state } = row;
      getStatusApi(id, mg_state).then((res) => {
        // console.log(res);
        if (res.data.meta.status == 200) {
          Message({
            message: res.data.meta.msg,
            type: "success",
          });
        } else {
          Message({
            message: res.data.meta.msg,
            type: "error",
          });
        }
      });
    },
    // 编辑操作
    handleEdit(index, row) {
      console.log(index, row);
      this.editFormVisible = true;
      this.addForm = row;
      this.currentId = row.id;
    },
    // 删除操作
    handleDelete(id) {
      deleteUsersApi(id).then((res) => {
        console.log(res);
        if (res.data.meta.status == 200) {
          Message({
            message: res.data.meta.msg,
            type: "success",
          });
        } else {
          Message({
            message: res.data.meta.msg,
            type: "error",
          });
        }
        this.getUsers();
      });
    },
    // 分页功能
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageinfo.pagesize = val;
      this.getUsers();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageinfo.pagenum = val;
      this.getUsers();
    },
  },
};
</script>
<style scoped lang="scss">
.cardbox {
  margin-top: 20px;
  .tablebox {
    margin: 20px 0;
  }
}
</style>
